import React, { PureComponent } from 'react';

class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      friends: [
        { name: "Lilei", age: 20 },
        { name: "Lily", age: 20 },
        { name: "Lucy", age: 20 },
      ]
    }
  }
  render() {
    // const { friends } = this.state
    return (
      <div>
        <h2>好友列表</h2>
        <ul>
          {
            this.state.friends.map((item, index) => {
              return (
                <li key={index}>
                  姓名：{item.name}
                  年龄：{item.age}
                  <button onClick={e=> this.incrementAge(index)}>年龄+1</button>
                </li>
              )
            })
          }
        </ul>
        <button onClick={e => this.inserDate()}>增加数据</button>
      </div>
    );
  }

  inserDate() {
    const newData = { name: "Tom", age: 30 }

    // 在开发中不要这样做
    // this.state.friends.push(newData)
    // this.setState({
    //   friends: this.state.friends
    // })

    //推荐做法
    const newFirends = [...this.state.friends]
    newFirends.push({ name: "Tom", age: 30 })
    this.setState({
      friends: newFirends
      // friends: [...this.state.friends, newData]
    })
  }
  incrementAge(index) { 
    const newFirends = [...this.state.friends]
    newFirends[index].age += 1
    this.setState({
      friends: newFirends
    })
  }
}

export default App;